package org.gdstash.character;

import org.gdstash.file.GDReader;
import org.gdstash.file.GDWriter;
import org.gdstash.util.FileVersionException;
import org.gdstash.util.GDMsgFormatter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class GDCharCrucible {
    private static final int VERSION = 2;
    private static final int BLOCK = 10;
    private int version;
    private ArrayList<List<String>> tokensPerDifficulty;

    public GDCharCrucible() {
        final int size = 3;
        this.tokensPerDifficulty = new ArrayList<List<String>>(size);
        for (int i = 0; i < size; ++i) {
            this.tokensPerDifficulty.add(new LinkedList<String>());
        }
    }

    public void read() throws IOException {
        int val = 0;
        final GDReader.Block block = new GDReader.Block();
        val = GDReader.readBlockStart(block);
        if (val != 10) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.version = GDReader.readEncInt(true);
        if (this.version != 2) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        for (int i = 0; i < this.tokensPerDifficulty.size(); ++i) {
            this.tokensPerDifficulty.get(i).clear();
            for (int num = GDReader.readEncInt(true), j = 0; j < num; ++j) {
                final String s = GDReader.readEncString();
                if (!this.tokensPerDifficulty.get(i).contains(s)) {
                    this.tokensPerDifficulty.get(i).add(s);
                }
            }
        }
        GDReader.readBlockEnd(block);
    }

    public void write() throws IOException {
        final GDReader.Block block = new GDReader.Block();
        GDWriter.writeBlockStart(block, 10);
        GDWriter.writeInt(this.version);
        for (int i = 0; i < this.tokensPerDifficulty.size(); ++i) {
            GDWriter.writeInt(this.tokensPerDifficulty.get(i).size());
            for (final String s : this.tokensPerDifficulty.get(i)) {
                GDWriter.writeString(s);
            }
        }
        GDWriter.writeBlockEnd(block);
    }

    public int getByteSize() {
        int size = 0;
        final int val = 0;
        size += 4;
        size += 4;
        size += 4;
        for (int i = 0; i < this.tokensPerDifficulty.size(); ++i) {
            size += 4;
            for (final String s : this.tokensPerDifficulty.get(i)) {
                size += 4;
                if (s != null) {
                    size += s.length();
                }
            }
        }
        size += 4;
        return size;
    }
}
